package com.kehutong.admin.service;

import com.kehutong.admin.entity.Corp;
import com.kehutong.admin.entity.Role;
import com.kehutong.admin.entity.RoleItem;
import com.kehutong.common.DoveClient;
import com.kehutong.common.errcode.Result;
import org.coraframework.bean.Beans;
import org.coraframework.bean.valid.ValidResult;
import org.coraframework.inject.Inject;
import org.coraframework.json.JSONArray;
import org.coraframework.json.JSONObject;
import org.coraframework.mvc.http.ReqMapping;
import org.coraframework.mvc.webservice.WebService;
import org.coraframework.orm.Pool;
import org.coraframework.orm.jdbc.JdbcSession;
import org.coraframework.orm.jdbc.execute.entity.FindArray;
import org.coraframework.orm.jdbc.execute.entity.FindOne;
import org.coraframework.util.Objects;

import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.List;

@WebService("/admin/service/role")
public class RoleService {

    @Inject
    private DoveClient doveClient;

    @Inject
    private CorpService corpService;

    @Inject
    private JdbcSession jdbcSession;

    @ReqMapping("/list")
    public Object list(JSONObject jsonObject){
        FindArray<Role> find = jdbcSession.findArray(Role.class)
                .eq("deleted", false)
                .eq(jsonObject, "companyNo");

        JSONArray ids = jsonObject.getJSONArray("ids");
        if(Objects.nonEmpty(ids)){
            find.markBegin();
            for (int i = 0; i < ids.size(); i++) {
                find.findInSet("id", ids.get(i)).or();
            }
            find.markEnd();
        }

        List<Role> list = find.exe();

        return Result.success(list);
    }

    public Object synRoles(JSONObject jsonObject){
       List<Corp> corps = (ArrayList) corpService.list(jsonObject);

       corps.forEach(corp->{
           String id = corp.getId() + "_" + 4;
           Role role = jdbcSession.findOne(Role.class).eq( "id", id).exe(false);

           if(Objects.nonNull(role)){
               List<RoleItem> roleItems = jdbcSession.findArray(RoleItem.class)
                       .in("id", role.getItems())
                       .exe();

               // 删除旧的角色权限信息
               if(Objects.nonEmpty(roleItems))
                   jdbcSession.deleteById(roleItems);

               // 获取新的权限信息
               Role initRole = jdbcSession.findById(Role.class, "4");
               if(Objects.nonEmpty(initRole.getItems())) {
                   List<RoleItem> tempItems = jdbcSession.findArray(RoleItem.class)
                           .in("id", initRole.getItems())
                           .exe();

                   List<String> ids = new ArrayList<>();
                   List<RoleItem> newItems = new ArrayList<>();
                   tempItems.forEach(template ->{
                       RoleItem item = Pool.newInstance(RoleItem.class);
                       Beans.from(template).to(item).exclude("id").copy();
                       item.setRoleId(id);
                       ids.add(item.getId());
                       newItems.add(item);
                   });
                   role.setItems(ids);
                   jdbcSession.insert(newItems);
               }
               jdbcSession.updateById(role);
           }
       });

       return Result.success();
    }

    @ReqMapping("/initCorp")
    public Object initCorp(JSONObject jsonObject){
        String companyNo = jsonObject.getString("companyNo");
        String id = companyNo + "_" + 4;
        Role role = jdbcSession.findOne(Role.class).eq( "id", id).exe(false);
        if (role == null) {
            role = Pool.newInstance(Role.class);
            Role initRole = jdbcSession.findById(Role.class, "4");
            Beans.from(initRole).to(role).copy();
            role.setId(id);
            role.setDeleted(false);
            role.setCompanyNo(companyNo);
            role.setCompanyName(jsonObject.getString("companyName"));
            role.setEmployeeNo(null);
            List<String> items = role.getItems();
            if(Objects.nonEmpty(items)){
                List<RoleItem> roleItems = jdbcSession.findArray(RoleItem.class)
                        .in("id", items)
                        .exe();

                List<String> ids = new ArrayList<>();
                List<RoleItem> newItems = new ArrayList<>();
                roleItems.forEach(template ->{
                    RoleItem item = Pool.newInstance(RoleItem.class);
                    Beans.from(template).to(item).exclude("id").copy();
                    item.setRoleId(id);
                    ids.add(item.getId());
                    newItems.add(item);
                });
                role.setItems(ids);
                jdbcSession.insert(newItems);
            }
            role.setName(role.getCompanyName() + "-客服");
            role.setCreateTime(new Timestamp(System.currentTimeMillis()));
            jdbcSession.insert(role);
        }
        return Result.success(id);
    }
}
